package cn.com.infcn.util;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Created by cc on 2016/12/29.
 * @author jijs
 */
public class FileUtils {

    private static SimpleDateFormat yyyyMMddFormat = new SimpleDateFormat("YYYY-MM-dd");
    private static SimpleDateFormat HHFormat = new SimpleDateFormat("HH");

    /**
     * 获取文件ID
     *
     * @return String 文件ID
     */
    private static String getFileId() {
        return UUID.randomUUID().toString();
    }

    /**
     * 获取文件路径
     *
     * @return String 临时目录/yyyyMMdd/HH/
     */
    public static String getFilePath() {
        String dir = ConfigUtils.getTempFileDirector();
        Date date = new Date();
        String dateStr = yyyyMMddFormat.format(date);
        String hour = HHFormat.format(date);
        File f = new File(dir + File.separator + dateStr + File.separator + hour);
        if(!f.exists()){
            f.mkdirs();
        }
        return f.getAbsolutePath() + File.separator + getFileId();
    }

    public static boolean deleteFile(File dir) {

        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            if (children != null) {
                for (String aChildren : children) {
                    boolean success = deleteFile(new File(dir, aChildren));
                    if (!success) {
                        return false;
                    }
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }
}